package com.jiedeng.controller.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jiedeng.controller.Rst;
import com.jiedeng.model.*;
import com.jiedeng.util.*;
import com.jiedeng.util.httpclient.HttpClientHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务管理
 *
 * @author zhouyb
 */
@Controller
@Scope("prototype")
@RequestMapping("/taskManage")
public class TaskManageController {
    @Value("${config.http.client.url}")
    public String url;
    //七牛网
    @Value("${config.prefix}")
    public String qnUrl;
    @Value("${config.winReporterPath}")
    private String winPath;
    @Value("${config.linuxReporterPath}")
    private String linuxPath;
    @Autowired
    CommonComponent commonComponent;

    /**
     * 任务管理首页
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/taskManageUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String taskManageUI(Model model, HttpServletRequest request, String type, String url, String taskType) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            //用户
            model.addAttribute("personName", SessionUtil.getUserNameSession());
            //单位
            model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());


            if ("2".equals(type)) {
                model.addAttribute("taskType", taskType);
                model.addAttribute("url", url + "&taskType=" + taskType);
            } else {
//                Rst rst = commonComponent.checkModuleRule("1030100");
//                if("OK".equals(rst.getMsg())){
                    model.addAttribute("taskType", 1);
                    model.addAttribute("url", "/taskManage/inspectTask");
//                }else{
//                    model.addAttribute("taskType", 2);
//                    model.addAttribute("url",  "/taskManage/rectificationTask");
//                }

            }
            //model.addAttribute("projectId", projectId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/task/taskHome";
    }

    /**
     * 检查任务
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/inspectTask", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String inspectTask(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize) {
        try {
            Rst rst = commonComponent.checkModuleRule("1030100");
            if(!"OK".equals(rst.getMsg())){
                return ForwardConstants.REDIRECT + "/jurisdictionBlank";
            }
            model.addAttribute("ctx", request.getContextPath());
            model.addAttribute("taskType", 1);
            String httpUrl = url + "/recorder/filterTaskManage?isDelete=false&&taskPersonId=" + SessionUtil.getUserIdSession()
                    + "&&excutePersonId=" + SessionUtil.getUserIdSession() +
                    "&&closePersonId=" + SessionUtil.getUserIdSession() +
                    "&&pubPersonId=" + SessionUtil.getUserIdSession() +
                    "&&verifyPersonId=" + SessionUtil.getUserIdSession() +
                    "&&page=" + page +
                    "&&pageSize=" + pageSize;
            String ret = HttpClientHelper.doGet(httpUrl);
            //String ret = HttpClientHelper.postRequest2(url + "/recorder/filterTask", map, "utf-8", "");
            List<Task> taskList = new ArrayList<>();
            if (ret != null) {
                List<Task> list = JSON.parseObject(ret.trim(), new TypeReference<List<Task>>() {
                });

                taskList = getTheCorrespondingTask(list, false, true, false, false, false);
            }
            //model.addAttribute("taskList", taskList);
            model.addAttribute("taskList", PageUtil.getTaskPage(taskList, Integer.parseInt(page), Integer.parseInt(pageSize)));
            model.addAttribute("count", taskList.size());
            model.addAttribute("maxPage", taskList.size() / Integer.parseInt(pageSize));
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            //model.addAttribute("query", query);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + taskList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "task/taskList";
    }

    /**
     * 整改任务
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/rectificationTask", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String rectificationTask(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize) {
        try {
            model.addAttribute("ctx", request.getContextPath());
            model.addAttribute("qnUrl", qnUrl);
            model.addAttribute("taskType", 2);
            String httpUrl = url + "/recorder/filterTaskManage?isDelete=false&&taskPersonId=" + SessionUtil.getUserIdSession()
                    + "&&excutePersonId=" + SessionUtil.getUserIdSession() +
                    "&&closePersonId=" + SessionUtil.getUserIdSession() +
                    "&&pubPersonId=" + SessionUtil.getUserIdSession() +
                    "&&verifyPersonId=" + SessionUtil.getUserIdSession();
            String ret = HttpClientHelper.doGet(httpUrl);
            //String ret = HttpClientHelper.postRequest2(url + "/recorder/filterTask", map, "utf-8", "");
            List<Task> taskList = new ArrayList<>();
            if (ret != null) {
                List<Task> list = JSON.parseObject(ret.trim(), new TypeReference<List<Task>>() {
                });

                taskList = getTheCorrespondingTask(list, false, true, true, false, false);
            }
            //model.addAttribute("taskList", taskList);
            model.addAttribute("taskList", PageUtil.getTaskPage(taskList, Integer.parseInt(page), Integer.parseInt(pageSize)));
            model.addAttribute("count", taskList.size());
            model.addAttribute("maxPage", taskList.size() / Integer.parseInt(pageSize));
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            //model.addAttribute("query", query);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + taskList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "task/taskList";
    }

    /**
     * 闭环任务
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/closedLoopTask", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String closedLoopTask(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize) {
        try {
            model.addAttribute("ctx", request.getContextPath());
            model.addAttribute("taskType", 3);
            String httpUrl = url + "/recorder/filterTaskManage?isDelete=false&&taskPersonId=" + SessionUtil.getUserIdSession()
                    + "&&excutePersonId=" + SessionUtil.getUserIdSession() +
                    "&&closePersonId=" + SessionUtil.getUserIdSession() +
                    "&&pubPersonId=" + SessionUtil.getUserIdSession() +
                    "&&verifyPersonId=" + SessionUtil.getUserIdSession();
            String ret = HttpClientHelper.doGet(httpUrl);
            //String ret = HttpClientHelper.postRequest2(url + "/recorder/filterTask", map, "utf-8", "");
            List<Task> taskList = new ArrayList<>();
            if (ret != null) {
                List<Task> list = JSON.parseObject(ret.trim(), new TypeReference<List<Task>>() {
                });

                taskList = getTheCorrespondingTask(list, false, true, true, true, true);
            }
            //model.addAttribute("taskList", taskList);
            model.addAttribute("taskList", PageUtil.getTaskPage(taskList, Integer.parseInt(page), Integer.parseInt(pageSize)));
            model.addAttribute("count", taskList.size());
            model.addAttribute("maxPage", taskList.size() / Integer.parseInt(pageSize));
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            //model.addAttribute("query", query);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + taskList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "task/taskList";
    }

    /**
     * 获取对应的任务
     *
     * @param tasks     任务列表
     * @param isDraft
     * @param isVerify
     * @param isClose
     * @param isCloseDo
     * @param isDo
     * @return
     */
    public List<Task> getTheCorrespondingTask(List<Task> tasks, boolean isDraft, boolean isVerify, boolean isClose, boolean isCloseDo, boolean isDo) {

        List<Task> taskList = new ArrayList<>();
        for (Task task : tasks) {
            if (task.isDraft() == isDraft && task.isVerify() == isVerify && task.isClose() == isClose && task.isCloseDo() == isCloseDo) {
                if (task.isDo()) {
                    task.setLoopDo("1");
                } else {
                    task.setLoopDo("0");
                }
                //只有闭环会为true  闭环isDo true和false 都可以
                if (isDo) {
                    taskList.add(task);
                } else {
                    if (!task.isDo()) {
                        taskList.add(task);
                    }
                }
            }
        }
        return taskList;
    }


    /**
     * 过滤check
     *
     * @param checks
     * @param isCloseFile
     * @return
     */
    public List<Check> getTheCorrespondingCheck(List<Check> checks, boolean isCloseFile) {


        List<Check> checkList = new ArrayList<>();
        for (Check check : checks) {
            if (check.isCloseFile() == isCloseFile) {
                checkList.add(check);
            }
        }
        return checkList;
    }

    /**
     * 分页列表数据
     *
     * @param checks
     * @param page
     * @param pageSize
     * @return
     */
    public List<Check> getCheckPage(List<Check> checks, int page, int pageSize) {
        int beginNum = (page - 1) * pageSize;
        int endNum = 0;
        if ((page) * pageSize < checks.size()) {
            endNum = (page ) * pageSize;
        } else {
            endNum = checks.size();
        }
        List<Check> checkList = new ArrayList<>();
        for (int i = beginNum; i < endNum; i++) {
            checkList.add(checks.get(i));
        }
        return checkList;
    }

    /**
     * 跳转添加任务页面
     *
     * @return
     */
    @RequestMapping(value = "/addTaskUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String addTaskUI(Model model, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("dataUrl", url);
        //用户
        model.addAttribute("personName", SessionUtil.getUserNameSession());
        model.addAttribute("personId", SessionUtil.getUserIdSession());
        //单位
        model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());
        return "task/releaseTask";
    }

    /**
     * 检查项
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkItem", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String checkItemUI(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize, String taskType, String taskId, @RequestParam(defaultValue = "1") String isSpot) {
        if (StringUtils.isEmpty(taskType)) {
            return ForwardConstants.REDIRECT + "/task/taskList";
        }
        model.addAttribute("qnUrl", qnUrl);
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("taskType", taskType);
        model.addAttribute("isSpot", isSpot);
        model.addAttribute("taskId", taskId);
        model.addAttribute("personId", Long.parseLong(SessionUtil.getUserIdSession()));
        model.addAttribute("url", url);
        //int type = Integer.parseInt(taskType);
        try {
            String retTask = HttpClientHelper.doGet(url + "/biz/task/findTaskById?id=" + taskId);
            Task task = JSON.parseObject(retTask.trim(), new TypeReference<Task>() {
            });
            task.setClosedLoop(task.isDo());
            model.addAttribute("task", task);
            Map<String, String> map = new HashMap<>();
            map.put("taskId", taskId);
            String ret = HttpClientHelper.postRequest2(url + "/taskManage/findCheckBytaskId", map, "utf-8", "");
            List<Check> checkList = new ArrayList<>();
            if (ret != null) {
                List<Check> checks = JSON.parseObject(ret.trim(), new TypeReference<List<Check>>() {
                });
                if ("1".equals(isSpot)) {
                    checkList = getTheCorrespondingCheck(checks, true);
                }
                if ("0".equals(isSpot)) {
                    checkList = getTheCorrespondingCheck(checks, false);
                }
                //taskList = getTheCorrespondingTask(list, false, true, true, true, true);
            }
            //model.addAttribute("taskList", taskList);
            model.addAttribute("checkList", getCheckPage(checkList, Integer.parseInt(page), Integer.parseInt(pageSize)));
            model.addAttribute("count", checkList.size());
            model.addAttribute("maxPage", checkList.size() / Integer.parseInt(pageSize));
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            //model.addAttribute("query", query);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + checkList.size());
            return "task/checkList";
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 跳转添加检查项页面
     *
     * @return
     */
    @RequestMapping(value = "/addCheckUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String addCheckUI(Model model, HttpServletRequest request, String taskId) {
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("dataUrl", url);
        model.addAttribute("taskId", taskId);
        try {

            //首页左边菜单
            String ret = HttpClientHelper.doGet(url + "/taskManage/getSpecMuneNew?taskId="+taskId);
//            String ret = HttpClientHelper.doGet(url + "/taskManage/getSpecMune");
            List<SpecMune> menus = JSON.parseObject(ret.trim(), new TypeReference<List<SpecMune>>() {
            });
            model.addAttribute("specMenu", menus);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "task/addCheck";
    }

    /**
     * 跳转添加亮点页面
     *
     * @return
     */
    @RequestMapping(value = "/addBrightStopUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String addBrightStopUI(Model model, HttpServletRequest request, String taskId) {
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("dataUrl", url);
        model.addAttribute("taskId", taskId);
        return "task/addBrightStop";
    }

    /**
     * 跳转详情
     *
     * @return
     */
    @RequestMapping(value = "/checkDetailsUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String checkDetailsUI(Model model, HttpServletRequest request, String checkId, String taskType) {
        model.addAttribute("ctx", request.getContextPath());
        //model.addAttribute("dataUrl", url);
        model.addAttribute("checkId", checkId);
        model.addAttribute("taskType", taskType);
        model.addAttribute("qnUrl", qnUrl);
        String ret = HttpClientHelper.doGet(url + "/recorder/checkDetail?checkId=" + checkId);
        Map<String, Object> detailMap = JSON.parseObject(ret.trim(), new TypeReference<Map<String, Object>>() {
        });
        //model.addAttribute("checkId", checkId);
        model.addAttribute("detailMap", detailMap);
        return "task/checkDetails";
    }

    /**
     * 跳转评分
     *
     * @return
     */
    @RequestMapping(value = "/scoreCheckUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String scoreCheckUI(Model model, HttpServletRequest request, String checkId, String taskType, String checkItemId) {
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("dataUrl", url);
        model.addAttribute("checkId", checkId);
        String ret = HttpClientHelper.doGet(url + "/checkitemRule/findCheckItemRuleByCheckItemId?checkItemId=" + checkItemId);
        List<CheckItemRule> checkItemRuleList = JSON.parseObject(ret.trim(), new TypeReference<List<CheckItemRule>>() {
        });

        String ret2 = HttpClientHelper.doGet(url + "/recorder/getCheckCounts?checkId=" + checkId);
        List<CheckCount> checkCountList = JSON.parseObject(ret2.trim(), new TypeReference<List<CheckCount>>() {
        });

        Map<String, List<CheckItemRule>> map = getResponsibilityList(checkItemRuleList);
        List<CheckItemRule> mainResponsibilityList = map.get("mainResponsibilityList");
        List<CheckItemRule> mainResponsibilityListPlus = map.get("mainResponsibilityListPlus");

        model.addAttribute("mainResponsibilityList", mainResponsibilityList);
        model.addAttribute("mainResponsibilityListPlus", mainResponsibilityListPlus);
        model.addAttribute("taskType", taskType);

        CheckCount checkCount = new CheckCount();
        CheckCount checkCount2 = new CheckCount();
        if (checkCountList != null && checkCountList.size() > 0) {
            for (CheckCount count : checkCountList) {
                if ("主要责任单位".equals(count.getCorpWeightLevel())) {
                    if (!StringUtils.isEmpty(count.getScoring())) {
                        checkCount = count;
                    }
                    if (!StringUtils.isEmpty(count.getScoring1())) {
                        checkCount2 = count;
                    }
                }
            }
        }
        boolean mainResponsibilityListCheck = mainResponsibilityList != null && mainResponsibilityList.size() > 0;
        boolean mainResponsibilityListPlusCheck = mainResponsibilityListPlus != null && mainResponsibilityListPlus.size() > 0;
        int scoreType = 0;
        if (mainResponsibilityListCheck && !mainResponsibilityListPlusCheck) {
            scoreType = 1;
        } else if (!mainResponsibilityListCheck && mainResponsibilityListPlusCheck) {
            scoreType = 2;
        } else if (mainResponsibilityListCheck && mainResponsibilityListPlusCheck) {
            scoreType = 3;
        }
        model.addAttribute("scoreType", scoreType);
        if (StringUtils.isEmpty(checkCount.getScoring())) {
            if (mainResponsibilityListCheck) {
                CheckItemRule checkItemRule = mainResponsibilityList.get(0);
                model.addAttribute("weighting", checkItemRule.getWeighting());
            } else {
                model.addAttribute("weighting", 0);
            }
        } else {
            model.addAttribute("weighting", checkCount.getScoring());

        }
        if (StringUtils.isEmpty(checkCount2.getScoring1())) {
            if (mainResponsibilityListPlusCheck) {
                CheckItemRule checkItemRule = mainResponsibilityListPlus.get(0);
                model.addAttribute("weight1", checkItemRule.getWeight1());
            } else {
                model.addAttribute("weight1", 0);
            }
        } else {
            model.addAttribute("weight1", checkCount2.getScoring1());
        }

        model.addAttribute("secondaryResponsibilityList", map.get("secondaryResponsibilityList"));
        model.addAttribute("relevantResponsibilityList", map.get("relevantResponsibilityList"));

        model.addAttribute("secondaryResponsibilityListPlus", map.get("secondaryResponsibilityListPlus"));
        model.addAttribute("relevantResponsibilityListPlus", map.get("relevantResponsibilityListPlus"));
        return "task/scoreCheck";
    }

    /**
     * 区分单位级别
     *
     * @param checkItemRuleList
     * @return
     */
    public Map<String, List<CheckItemRule>> getResponsibilityList(List<CheckItemRule> checkItemRuleList) {
        Map<String, List<CheckItemRule>> map = new HashMap<String, List<CheckItemRule>>();
        List<CheckItemRule> mainResponsibilityList = new ArrayList<>();
        List<CheckItemRule> secondaryResponsibilityList = new ArrayList<>();
        List<CheckItemRule> relevantResponsibilityList = new ArrayList<>();

        List<CheckItemRule> mainResponsibilityListPlus = new ArrayList<>();
        List<CheckItemRule> secondaryResponsibilityListPlus = new ArrayList<>();
        List<CheckItemRule> relevantResponsibilityListPlus = new ArrayList<>();
        for (CheckItemRule checkItemRule : checkItemRuleList) {
            if (checkItemRule.getPostId() == -2) {
                continue;
            }
            if ("主要责任单位".equals(checkItemRule.getCorpWeightLevel())) {
                if (!StringUtils.isEmpty(checkItemRule.getWeighting())) {
                    mainResponsibilityList.add(checkItemRule);
                } else {
                    mainResponsibilityListPlus.add(checkItemRule);

                }
            }
            if ("次要责任单位".equals(checkItemRule.getCorpWeightLevel())) {
                if (!StringUtils.isEmpty(checkItemRule.getWeighting())) {
                    secondaryResponsibilityList.add(checkItemRule);
                } else {
                    secondaryResponsibilityListPlus.add(checkItemRule);

                }
            }
            if ("相关责任单位".equals(checkItemRule.getCorpWeightLevel())) {

                if (!StringUtils.isEmpty(checkItemRule.getWeighting())) {
                    relevantResponsibilityList.add(checkItemRule);
                } else {
                    relevantResponsibilityListPlus.add(checkItemRule);

                }
            }
        }
        map.put("mainResponsibilityList", mainResponsibilityList);
        map.put("secondaryResponsibilityList", secondaryResponsibilityList);
        map.put("relevantResponsibilityList", relevantResponsibilityList);
        map.put("mainResponsibilityListPlus", mainResponsibilityListPlus);
        map.put("secondaryResponsibilityListPlus", secondaryResponsibilityListPlus);
        map.put("relevantResponsibilityListPlus", relevantResponsibilityListPlus);
        return map;
    }

    /**
     * 评分
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("addScore")
    public String addScore() {
        String responsibilityCorpPersonIds = SessionUtil.getPara("responsibilityCorpPersonIds");
        String scoreNum = SessionUtil.getPara("scoreNum");
        String deductionNum = SessionUtil.getPara("deductionNum");
        String checkId = SessionUtil.getPara("checkId");
        Map<String, String> map = new HashMap<String, String>();
        String ret = null;
        try {
            map.put("responsibilityCorpPersonIds", responsibilityCorpPersonIds);
            map.put("scoreNum", scoreNum);
            map.put("deductionNum", deductionNum);
            map.put("checkId", checkId);
            ret = HttpClientHelper.postRequest2(url + "/taskManage/addCheckCountEntitys", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            if (rst.getResultCode() == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return ForwardConstants.ERROR;
    }

    /**
     * 新增任务
     *
     * @param projectId      项目id
     * @param projectName    项目名称
     * @param stageID        项目阶段id
     * @param propName       库名称
     * @param taskCorpId     责任单位
     * @param taskPersonId   责任人
     * @param startTime      开始时间
     * @param endTime        结束时间
     * @param excutePersonId 检查人
     * @return
     */
    @ResponseBody
    @RequestMapping("addTask")
    public String addTask(String projectId, String projectName, String stageID, String propName, String taskCorpId, String taskPersonId, String startTime, String endTime, String excutePersonId, String propId) {

        //Task task = new Task();
        //task.setPubCorpId(person.getCorpId());
        //task.setPubPersonId(person.getId());
        //task.setId(UUID.randomUUID().toString());
        //task.setProjectId(Integer.parseInt(projectId));
        //task.setStageID(Long.parseLong(stageID));
        //task.setCaption(caption);
        //task.setTaskCorpId(Long.parseLong(taskCorpId));
        //task.setTaskPersonId(Long.parseLong(taskPersonId));
        //task.setStartTime(DatetimeUtil.formartDate("yyyy-MM-dd HH:mm:ss", startTime, 0));
        //task.setEndTime(DatetimeUtil.formartDate("yyyy-MM-dd HH:mm:ss", endTime, 0));
        //task.setExcutePersonId(excutePersonId);
        try {
            Map<String, String> map = new HashMap<String, String>();
            String caption = projectName + "/" + DatetimeUtil.getDateyyyyMMdd() + "/" + propName;
            Person person = (Person) SessionUtil.getUserSession();
            map.put("projectId", projectId);
            map.put("stageID", stageID);
            map.put("propId", propId);
            map.put("caption", caption);
            map.put("taskCorpId", taskCorpId);
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            map.put("excutePersonId", excutePersonId);
            map.put("taskPersonId", taskPersonId);
            map.put("pubPersonId", person.getId() + "");
            map.put("pubCorpId", person.getCorpId() + "");
            String ret = HttpClientHelper.postRequest2(url + "/taskManage/addTaskEntity", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 新增检查项
     *
     * @param expressionDesc 检查内容
     * @param file           检查图
     * @param checkItemId    检查项
     * @param taskId         任务id
     * @param isCloseFile    是否亮点
     * @return
     */
    @ResponseBody
    @RequestMapping("addCheck")
    public String addCheck(String expressionDesc, @RequestParam(value = "file", required = false) MultipartFile file, String checkItemId, String taskId, String isCloseFile, @RequestParam(value = "file2", required = false) MultipartFile file2, @RequestParam(value = "file3", required = false) MultipartFile file3, HttpServletRequest request) {
        try {
            Person person = (Person) SessionUtil.getUserSession();
            Map<String, String> map = new HashMap<String, String>();
            if (file != null && !file.isEmpty()) {
                String suff = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                String keyName = person.getId() + "_1" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_JC." + suff;
                uploadFileCheck(file, keyName, request);
                map.put("expressionDescPath", keyName);
            }
            if (file2 != null && !file2.isEmpty()) {
                String suff2 = file2.getOriginalFilename().substring(file2.getOriginalFilename().lastIndexOf(".") + 1);
                String keyName2 = person.getId() + "_2" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_JC." + suff2;
                uploadFileCheck(file2, keyName2, request);
                map.put("expressionDescPath2", keyName2);
            }
            if (file3 != null && !file3.isEmpty()) {
                String suff3 = file3.getOriginalFilename().substring(file3.getOriginalFilename().lastIndexOf(".") + 1);
                String keyName3 = person.getId() + "_3" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_JC." + suff3;
                uploadFileCheck(file3, keyName3, request);
                map.put("expressionDescPath3", keyName3);
            }
            /*
            String suff2 = file.getOriginalFilename().substring(file2.getOriginalFilename().lastIndexOf(".") + 1);
            String keyName2 = person.getId() + "_" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_LD." + suff2;
            qiniuUtil.uploadFile(file2, keyName2);*/

            //map.put("projectId", projectId);
            map.put("taskId", taskId);
            if (!StringUtils.isEmpty(checkItemId)) {
                map.put("checkItemId", checkItemId);
            }
            map.put("personId", person.getId() + "");
            map.put("expressionDesc", expressionDesc);

            map.put("isCloseFile", isCloseFile);
            //map.put("recordText", recordText);
            //map.put("spotPath", keyName2);//亮点图片
            String ret = HttpClientHelper.postRequest2(url + "/taskManage/addCheckEntity", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 上传文件
     *
     * @param file
     * @param keyName
     * @throws IOException
     */
    public void uploadFileCheck(MultipartFile file, String keyName, HttpServletRequest request) throws IOException {
        int maxSize = 1024 * 1024;
        QiniuUtil qiniuUtil = new QiniuUtil();
        //System.out.println(file.getOriginalFilename());
        if (file.getSize() > maxSize) {
            String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
            File dir = new File(filePath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            String path = filePath + file.getOriginalFilename();
            File tempFile = null;
            //save to the /upload path
            tempFile = new File(path);
            file.transferTo(tempFile);
            String newPath = "";
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
                newPath = winPath;
            } else {
                newPath = linuxPath;
            }
            //String suff = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String originaImagePath = newPath + keyName;
            File originalImage = new File(originaImagePath);
            ImageUtil.zoomImage(tempFile, originalImage, 1024);
            //ImageUtil.resize(tempFile, originalImage, 1000, 1f);
            qiniuUtil.upload(originaImagePath, keyName);
        } else {
            qiniuUtil.uploadFile(file, keyName);
        }
    }

    /**
     * 跳转到开具整改单页面
     *
     * @param model
     * @param taskId
     * @param request
     * @return
     */
    @RequestMapping("setChangeUI")
    public String setChangeUI(Model model, String taskId, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("taskId", taskId);
        model.addAttribute("dataUrl", url);
        return "/task/setChange";
    }

    /**
     * 开具整改
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("setChange")
    public String setChange(HttpServletRequest request) {
        try {
            String taskId = request.getParameter("taskId");
            String taskCorpId = request.getParameter("taskCorpId");
            String taskPersonId = request.getParameter("taskPersonId");
            String completeTime = request.getParameter("completeTime");
            Map<String, String> map = new HashMap<String, String>();
            map.put("taskId", taskId);
            map.put("taskCorpId", taskCorpId);
            map.put("taskPersonId", taskPersonId);
            map.put("completeTime", completeTime);
            String ret = HttpClientHelper.postRequest2(url + "/taskManage/setChange", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            Map<String, String> map2 = new HashMap<String, String>();
            map2.put("taskId", taskId);
            map2.put("type", "2");//整改
            map2.put("personId", SessionUtil.getUserIdSession());
            HttpClientHelper.postRequest2(url + "/message/saveMsg", map2, "utf-8", "");
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
            return ForwardConstants.ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
    }

    /**
     * 删除检查
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteCheck")
    public String deleteCheck(HttpServletRequest request) {
        try {
            String checkIds = request.getParameter("checkIds");
            Map<String, String> map = new HashMap<String, String>();
            map.put("checkIds", checkIds);
            String ret = HttpClientHelper.postRequest2(url + "/taskManage/deleteCheck", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
            return ForwardConstants.ERROR;
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
    }

    /**
     * 打回按钮
     *
     * @param request
     * @return
     */
    @RequestMapping("isReturn")
    public String isReturn(Model model, HttpServletRequest request, String taskId) {
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("taskId", taskId);
        return "task/isReturn";
    }


    /**
     * 打回
     *
     * @param model
     * @param request
     * @param taskId
     * @param reason
     * @return
     */
    @ResponseBody
    @RequestMapping("submitReturn")
    public String submitReturn(Model model, HttpServletRequest request, String taskId, String reason) {
        try {
            model.addAttribute("ctx", request.getContextPath());
            Map<String, String> map = new HashMap<String, String>();
            map.put("taskId", taskId);
            map.put("reason", reason);
            String ret = HttpClientHelper.postRequest2(url + "/taskManage/submitReturn", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            Map<String, String> map2 = new HashMap<String, String>();
            map2.put("taskId", taskId);
            //map2.put("reason", reason);
            map2.put("opinion", reason);
            map2.put("type", "4");//打回
            map2.put("personId", SessionUtil.getUserIdSession());
            HttpClientHelper.postRequest2(url + "/message/saveMsg", map2, "utf-8", "");
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 整改页面
     *
     * @param request
     * @return
     */
    @RequestMapping("changeOptionUI")
    public String changeOptionUI(Model model, HttpServletRequest request, String checkId) {
        model.addAttribute("ctx", request.getContextPath());
        //model.addAttribute("dataUrl", url);
        model.addAttribute("checkId", checkId);
        model.addAttribute("taskType", 2);
        model.addAttribute("qnUrl", qnUrl);
        String ret = HttpClientHelper.doGet(url + "/recorder/checkDetail?checkId=" + checkId);
        Map<String, Object> detailMap = JSON.parseObject(ret.trim(), new TypeReference<Map<String, Object>>() {
        });
        model.addAttribute("detailMap", detailMap);
        return "task/changeOption";
    }

    /**
     * 检查整改
     *
     * @param changeId
     * @param file
     * @param closeMemo
     * @return
     */
    @ResponseBody
    @RequestMapping("addCheckChange")
    public String addCheckChange(String changeId, @RequestParam(value = "imgFile1", required = false) MultipartFile file, String closeMemo, @RequestParam(value = "imgFile2", required = false) MultipartFile file2, @RequestParam(value = "imgFile3", required = false) MultipartFile file3, HttpServletRequest request, String delPhotoId) {
        try {
            Person person = (Person) SessionUtil.getUserSession();
            Map<String, String> map = new HashMap<String, String>();
            if (file != null && !file.isEmpty()) {
                String suff = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                String keyName = person.getId() + "_1" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_ZG." + suff;
                uploadFileCheck(file, keyName, request);
                map.put("expressionDescPath", keyName);
            }
            if (file2 != null && !file2.isEmpty()) {
                String suff2 = file2.getOriginalFilename().substring(file2.getOriginalFilename().lastIndexOf(".") + 1);
                String keyName2 = person.getId() + "_2" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_ZG." + suff2;
                uploadFileCheck(file2, keyName2, request);
                map.put("expressionDescPath2", keyName2);
            }
            if (file3 != null && !file3.isEmpty()) {
                String suff3 = file3.getOriginalFilename().substring(file3.getOriginalFilename().lastIndexOf(".") + 1);
                String keyName3 = person.getId() + "_3" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_ZG." + suff3;
                uploadFileCheck(file3, keyName3, request);
                map.put("expressionDescPath3", keyName3);
            }
            map.put("delPhotoIds", delPhotoId);
            map.put("checkId", changeId);
            map.put("personId", person.getId() + "");
            map.put("closeMemo", closeMemo);

            String ret = HttpClientHelper.postRequest2(url + "/taskManage/addCheckChange", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 整改提交
     *
     * @param taskId
     * @return
     */
    @ResponseBody
    @RequestMapping("changeSubmit")
    public String changeSubmit(String taskId) {
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("taskId", taskId);
            String ret = HttpClientHelper.postRequest2(url + "/taskManage/changeSubmit", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
            Map<String, String> map2 = new HashMap<String, String>();
            map2.put("taskId", taskId);
            map2.put("type", "3");//已整改
            map2.put("personId", SessionUtil.getUserIdSession());
            HttpClientHelper.postRequest2(url + "/message/saveMsg", map2, "utf-8", "");
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 任务闭环
     *
     * @param taskId
     * @return
     */
    @ResponseBody
    @RequestMapping("taskClose")
    public String taskClose(String taskId) {
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("taskId", taskId);
            String ret = HttpClientHelper.postRequest2(url + "/taskManage/taskClose", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 修改
     *
     * @param expressionDesc 检查内容
     * @param file           检查图
     * @param checkId
     * @param file2
     * @param file3
     * @param request
     * @param delPhotoId     删除的照片ids
     * @return
     */
    @ResponseBody
    @RequestMapping("editCheck")
    public String editCheck(String expressionDesc, @RequestParam(value = "file1", required = false) MultipartFile file, String checkId, @RequestParam(value = "file2", required = false) MultipartFile file2, @RequestParam(value = "file3", required = false) MultipartFile file3, HttpServletRequest request, String delPhotoId) {
        try {
            Person person = (Person) SessionUtil.getUserSession();
            Map<String, String> map = new HashMap<String, String>();
            if (file != null && !file.isEmpty()) {
                String suff = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                String keyName = person.getId() + "_1" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_JC." + suff;
                map.put("expressionDescPath", keyName);
                uploadFileCheck(file, keyName, request);
            }
            if (file2 != null && !file2.isEmpty()) {
                String suff2 = file2.getOriginalFilename().substring(file2.getOriginalFilename().lastIndexOf(".") + 1);
                String keyName2 = person.getId() + "_2" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_JC." + suff2;
                map.put("expressionDescPath2", keyName2);
                uploadFileCheck(file2, keyName2, request);
            }
            if (file3 != null && !file3.isEmpty()) {
                String suff3 = file3.getOriginalFilename().substring(file3.getOriginalFilename().lastIndexOf(".") + 1);
                String keyName3 = person.getId() + "_3" + DatetimeUtil.getDateyyyyMMddhhmmss() + "_JC." + suff3;
                map.put("expressionDescPath3", keyName3);
                uploadFileCheck(file3, keyName3, request);
            }
            map.put("personId", SessionUtil.getUserIdSession());
            map.put("checkId", checkId);
            map.put("expressionDesc", expressionDesc);
            map.put("delPhotoId", delPhotoId);
            String ret = HttpClientHelper.postRequest2(url + "/taskManage/editCheckEntity", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            int code = rst.getResultCode();
            if (code == 0) {
                return ForwardConstants.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.ERROR;
    }


}
